package com.syj.web.controller;

import com.syj.core.result.ReturnData;
import com.syj.core.result.ReturnEnum;
import com.syj.core.variable.SessionUtil;
import com.syj.web.model.User;
import com.syj.web.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author rankai
 *         createTime 2017-02-2017/2/8 12:34
 */
@Controller
@RequestMapping("/login")
public class LogonController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage() {
        return "/login";
    }

    @PostMapping
    @ResponseBody
    public ReturnData login(@RequestParam String userName, @RequestParam String password) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
            return new ReturnData(ReturnEnum.PARAMETER_ERROR.getCode()).setMsg("用户名或密码不能为空");
        }
        User user = new User();
        user.setUsername(userName);
        User userOne = userService.selectOne(user);
        if (userOne != null) {
            if (password.equals(userOne.getPassword())) {
                if (userOne.getStatus() == 1) {
                    SessionUtil.getRequest().getSession().setAttribute("user", userOne);
                    return new ReturnData().setData(userOne.getIsAdmin());
                }
                return new ReturnData(400).setMsg("该帐号被停用");
            }
            return new ReturnData(400).setMsg("密码错误");
        }
        return new ReturnData(400).setMsg("账号不存在");
    }

    @GetMapping("/out")
    public String loginOut() {
        return "redirect:/";
    }
}
